import {
  Descriptions,
  Table,
  Typography,
  Input,
  Form,
  Button,
  Space,
  message,
} from "antd";
import React, {
  Component,
  useContext,
  useState,
  useEffect,
  useRef,
} from "react";
import { Inquirydetail, Inquiryedit } from "../../../services/auth";
import "./index.css";

const { Text } = Typography;
const EditableContext = React.createContext(null);
const EditableRow = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};

const EditableCell = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef(null);
  const form = useContext(EditableContext);
  useEffect(() => {
    if (editing) {
      inputRef.current.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({
      [dataIndex]: record[dataIndex],
    });
  };

  const save = async () => {
    try {
      const values = await form.validateFields();
      toggleEdit();
      handleSave({ ...record, ...values });
    } catch (errInfo) {
      console.log("Save failed:", errInfo);
    }
  };

  let childNode = children;

  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{
          margin: 0,
        }}
        name={dataIndex}
        rules={[
          {
            required: true,
            message: `${title} is required.`,
          },
        ]}
      >
        <Input ref={inputRef} onPressEnter={save} onBlur={save} />
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{
          paddingRight: 24,
        }}
        onClick={toggleEdit}
      >
        {children}
      </div>
    );
  }

  return <td {...restProps}>{childNode}</td>;
};

export default class Inquiry_edit extends Component {
  constructor(props) {
    super(props);
    this.columns = [
      {
        title: "产品编号",
        dataIndex: "goods_id",
        key: "goods_id",
        align: "center",
      },
      {
        title: "产品名称",
        dataIndex: "goods_name",
        key: "goods_name",
        align: "center",
      },
      {
        title: "订货数量",
        dataIndex: "quatity",
        key: "quatity",
        align: "center",
      },
      {
        title: "产品定价（件/元）",
        dataIndex: "price",
        key: "price",
        align: "center",
      },
      {
        title: "订单转化率",
        dataIndex: "trans_rate",
        key: "trans_rate",
        align: "center",
        width: "15%",
        editable: true,
      },
      {
        title: "产品期望价格（件/元）",
        dataIndex: "expectprice",
        key: "expectprice",
        align: "center",
      },
    ];
    this.state = {
      data: {}, //询价单整体
      arr: [],
      dataSource: [], //商品列表
      count: 2,
    };
  }
  componentWillMount() {
    const { id } = this.props;
    Inquirydetail(id).then(
      (response) => {
        console.log(response.data); ////查看后台数据
        //拿到我们想要渲染的数据(res)
        this.state.arr = response.data; //更新state，让视图刷新
        this.setState({
          data: this.state.arr,
          dataSource: this.state.arr.goods,
        });
      },
      (error) => {
        console.log("失败了", error);
      }
    );
  }
  handleSave = (row) => {
    const newData = [...this.state.dataSource];
    const index = newData.findIndex((item) => row.goods_id === item.goods_id);
    const item = newData[index];
    row.expectprice = (row.price * row.trans_rate) / 100; //自动生成价格
    newData.splice(index, 1, { ...item, ...row }); //删去item,把row填进去
    this.setState({
      dataSource: newData,
    });
  };

  render() {
    const { data, dataSource } = this.state;
    const components = {
      body: {
        row: EditableRow,
        cell: EditableCell,
      },
    };
    const columns = this.columns.map((col) => {
      if (!col.editable) {
        return col;
      }

      return {
        ...col,
        onCell: (record) => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    return (
      <div>
        <Descriptions layout="vertical" column={4}>
          <Descriptions.Item label="询价单编号">{data.id}</Descriptions.Item>
          <Descriptions.Item label="公司名称">
            {data.company_name}
          </Descriptions.Item>
          <Descriptions.Item label="操作员">
            {data.operator_id}
          </Descriptions.Item>
          <Descriptions.Item>
            <Space size="middle">
              <Button
                type="primary"
                onClick={() => {
                  const inquiryid = data.id;
                  Inquiryedit({ inquiryid, dataSource }).then(
                    (response) => {
                      console.log(response.data); //查看是否成功
                      message.success("保存成功！");
                    },
                    (error) => {
                      console.log("失败了", error);
                    }
                  );
                }}
              >
                保存
              </Button>
            </Space>
          </Descriptions.Item>
          <Descriptions.Item label="询价日期">
            {data.valid_from}
          </Descriptions.Item>
          <Descriptions.Item label="询价有效期至">
            {data.valid_to}
          </Descriptions.Item>
          <Descriptions.Item label="预计送达日期">
            {data.req_deliv_date}
          </Descriptions.Item>
          <Descriptions.Item label="预计送货地点">
            {data.ship_to_address}
          </Descriptions.Item>
        </Descriptions>
        <Table
          dataSource={dataSource}
          columns={columns}
          components={components}
          rowKey={(record) => record.goods_id}
          rowClassName={() => "editable-row"}
          pagination={false}
          bordered
          summary={(pageData) => {
            let totalQuatity = 0;
            let totalPrice = 0;
            let totalExpectprice = 0;

            pageData.forEach(({ quatity, price, expectprice }) => {
              totalQuatity += quatity * 1;
              totalPrice += quatity * price;
              totalExpectprice += quatity * expectprice;
            });
            return (
              <>
                <Table.Summary.Row>
                  <Table.Summary.Cell align="center">合计</Table.Summary.Cell>
                  <Table.Summary.Cell></Table.Summary.Cell>
                  <Table.Summary.Cell align="center">
                    <Text type="danger">{totalQuatity}</Text>
                  </Table.Summary.Cell>
                  <Table.Summary.Cell align="center">
                    <Text type="danger">{totalPrice}</Text>
                  </Table.Summary.Cell>
                  <Table.Summary.Cell></Table.Summary.Cell>
                  <Table.Summary.Cell align="center">
                    <Text type="danger">{totalExpectprice}</Text>
                  </Table.Summary.Cell>
                </Table.Summary.Row>
              </>
            );
          }}
        />
        ;
      </div>
    );
  }
}
